package com.yricky.indesk.model

import com.yricky.indesk.model.pojo.DesktopConfig
import com.yricky.indesk.utils.*
import me.yricky.event.Audience
import java.io.File

/**
 * @author Yricky
 * @date 2021/12/26
 */
class AppConfig(private val f:File) {
    init {
        if(!f.exists()){ f.mkdirs() }
    }
    private val cfgFile get() = File(f,"cfg")
    private val dCfgDir get() = File(f,"desktopCfg").also {
        if(!it.exists()) { it.mkdirs() }
    }


    data class Config(
        val autoRemoveInvalidShortcut:Boolean = false,
        val desktopConfigFile:String = "default"
    )
    var config:Config = try {
            gson.fromJson(cfgFile.readText(),Config::class.java)
        }catch (e:Throwable){
            Config().also {
                cfgFile.writeText(gson.toJson(it))
            }
        }
        private set(value) {
            cfgFile.writeText(gson.toJson(value))
            desktopConfig = loadDCfg()
            cfgChannel.post(CfgEvent.CfgChanged)
            field = value
        }

    var desktopConfig:DesktopConfig = loadDCfg()
    set(value) {
        File(dCfgDir,config.desktopConfigFile).writeText(gson.toJson(value))
        field = value
        postCfgEvent(CfgEvent.DCfgChanged)
    }

    private fun loadDCfg():DesktopConfig = try{
        gson.fromJson(File(dCfgDir,config.desktopConfigFile).readText(),DesktopConfig::class.java)
    }catch (e:Throwable){
        DesktopConfig(5,5, getAllApps().chunked(25)).also {
            File(dCfgDir,config.desktopConfigFile).writeText(gson.toJson(it))
        }
    }




    /**
     * AppConfig 只对消息总线中包相关消息感兴趣
     */
    val audience: Audience<PkgEvent> = Audience.Msg<PkgEvent>().also { a ->
        a.attach { event->
            when(event){
                is PkgEvent.PkgInstalled ->{
                    desktopConfig = desktopConfig.addEntrance(getEntrance(event.pkgName))
                }
                is PkgEvent.PkgUninstalled ->{
                    desktopConfig = desktopConfig.removeInvalidItem()
                }
            }
        }
    }

}